<template>
    <div class="erpInfoBaseDepot-container flex flex-col">
        <a-card class="mb-2.5">
            <common-form :model="state.queryForm" name="menu-form" @query="handleQuery" @add="handleAdd"
                @reset="handleReset">
                <a-form-item label="仓库名称" name="name" class="w-1/2.5">
                    <a-input v-model:value="state.queryForm.name" placeholder="请输入仓库名称" />
                </a-form-item>
            </common-form>
        </a-card>
        <a-card class="flex-1 card-table">
            <common-table :columns="columns" :data="state.tableData" :pagination="{
                total: state.tableParams.total,
                current: state.tableParams.page,
                pageSize: state.tableParams.pageSize,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['2', '5', '10', '20'],
                showTotal: (total: number) => `总数: ${total}`
            }" :loading="state.loading" @change="changePagination">
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'operation'">
                        <div class="w-full">
                            <a-button ghost type="primary" class="mr-1" @click="handleEdit(record)">编辑</a-button>
                            <a-button danger type="primary" class="mr-1" @click="handleDelete(record)">删除</a-button>
                        </div>
                    </template>
                    <template v-else-if="column.dataIndex == 'enabled'">
                        <a-tag v-if="record.enabled" color="green">启用</a-tag>
                        <a-tag v-else color="red">停用</a-tag>
                    </template>
                    <template v-else-if="column.dataIndex == 'isDefault'">
                        <a-switch v-model:checked="record.isDefault" checked-children="是" un-checked-children="否"
                            size="small" @change="handleDefaultChange(record)"/>
                    </template>
                </template>
            </common-table>
        </a-card>
        <a-modal v-model:open="state.isShow" :title="state.isEdit ? '编辑' : '新增'" @ok="handleAddEdit"
            @cancel="handleCancel">
            <a-form ref="formRef" :model="state.formState" name="basinfo-form" autocomplete="off"
                :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <a-form-item label="仓库名称" name="name"
                    :rules="[{ required: true, message: '仓库名称不能为空', trigger: 'blur' }]">
                    <a-input v-model:value="state.formState.name" placeholder="请输入仓库名称" />
                </a-form-item>
                <a-form-item label="仓库地址" name="address">
                    <a-input v-model:value="state.formState.address" placeholder="请输入仓库地址" />
                </a-form-item>
                <a-form-item label="负责人" name="directorName" :rules="[{ required: true, message: '负责人不能为空', trigger: 'blur' }]">
                    <a-input v-model:value="state.formState.directorName" placeholder="负责人" allow-clear
                        @click="selectUsers" />
                </a-form-item>
                <a-form-item label="仓储费" name="warehousing">
                    <!-- <a-input v-model:value="state.formState.warehousing" placeholder="请输入仓储费" /> -->
                    <a-input-number class="w-full" :min="0" :precision="6" v-model:value="state.formState.warehousing" placeholder="请输入仓储费" />
                </a-form-item>
                <a-form-item label="搬运费" name="truckage">
                    <!-- <a-input v-model:value="state.formState.truckage" placeholder="请输入搬运费" /> -->
                    <a-input-number class="w-full" :min="0" :precision="6" v-model:value="state.formState.truckage" placeholder="请输入搬运费" />
                </a-form-item>
                <a-form-item label="描述" name="remark">
                    <a-textarea v-model:value="state.formState.remark" placeholder="请输入描述" />
                </a-form-item>
                <a-form-item label="启用" name="enabled">
                    <a-switch v-model:checked="state.formState.enabled" />
                </a-form-item>
            </a-form>
        </a-modal>
        <select-dept-users ref="selectDeptUsersRef" @save="handleSaveDeptUsers" mode="single" />
    </div>
</template>


<script setup lang="ts" name="ErpInfoBaseDepot">
import { ref, reactive, onMounted, useTemplateRef } from 'vue'
import CommonForm from '@/components/common-form/index.vue'
import CommonTable from '@/components/common-table/index.vue'
import {
    getInfoBaseDepotListApi,
    addInfoBaseDepotApi,
    deleteInfoBaseDepotApi,
    updateInfoBaseDepotApi,
    updateInfoBaseDefaultApi
} from '@/api/erp/infobase/index'
import type { ResType } from '@/api/types'
import type { FormInstance } from 'ant-design-vue'
import { showMsg } from '@/utils'
import selectDeptUsers from '@/components/select-org-user/index.vue'

defineOptions({
    name: "ErpInfoBaseDepot"
})

const formRef = ref<FormInstance>()
const selectDeptUsersRef = useTemplateRef("selectDeptUsersRef")

const state = reactive({
    queryForm: {
        name: ""
    } as any,
    tableData: [] as any[],
    tableParams: {
        page: 1,
        pageSize: 50,
        total: 0 as any,
    },
    formState: {
    } as any,
    loading: false,
    isShow: false,
    isEdit: false
})

const columns: any[] = [
    {
        title: '序号',
        align: "center",
        width: 60,
        customRender: ({ index }: { index: number }) => {
            return `${index + 1}`;
        },
        fixed: 'left',
    },
    {
        title: '仓库名称',
        align: "center",
        key: "name",
        dataIndex: 'name',
        width: 150,
    },
    {
        title: '仓库地址',
        align: "center",
        key: "address",
        dataIndex: 'address',
        width: 200,
    },
    {
        title: '仓储费',
        align: "center",
        key: "warehousing",
        dataIndex: 'warehousing',
        width: 120,
    },
    {
        title: '搬运费',
        align: "center",
        key: "truckage",
        dataIndex: 'truckage',
        width: 120,
    },
    {
        title: '描述',
        align: "center",
        key: "remark",
        dataIndex: 'remark',
        width: 200,
    },
    {
        title: '状态',
        align: "center",
        key: "enabled",
        dataIndex: 'enabled',
        width: 120,
    },
    {
        title: '是否默认',
        align: "center",
        key: "isDefault",
        dataIndex: 'isDefault',
        width: 120,
    },
    {
        title: '操作',
        align: 'center',
        key: "operation",
        dataIndex: 'operation',
        width: 250,
        fixed: 'right',
    }
]
const handleDefaultChange =async (record:any)=>{
    const res: ResType<any> = await updateInfoBaseDefaultApi({
        id: record.id,
    })
    if (res.data.code == 200) {
        showMsg("操作成功", 'success')
        await handleQuery()
    }
}

const handleSaveDeptUsers = (val: any) => {
    state.formState.principal = val[0].id
    state.formState.directorName = val[0].realName
    formRef.value?.clearValidate("principal")
}
const selectUsers = ()=>{
    selectDeptUsersRef.value?.handleOpen(state.formState.principal)
}
const handleQuery = async () => {
    state.loading = true
    const params = Object.assign(state.tableParams, state.queryForm)
    const res: ResType<any> = await getInfoBaseDepotListApi(params)
    state.tableData = res.data.result.items
    state.tableParams.total = res.data.result.total
    state.loading = false
}

const handleAdd = async () => {
    state.formState = {
    }
    state.isShow = true
    state.isEdit = false
}

const handleReset = async () => {
    state.queryForm = {
        name: ""
    }
    state.tableParams.page = 1
    await handleQuery()
}

const handleAddEdit = async () => {
    await formRef.value?.validate()
    if (state.isEdit && state.formState.id) {
        const res: ResType<any> = await updateInfoBaseDepotApi(state.formState)
        if (res.data.code == 200) {
            showMsg("编辑成功", 'success')
            handleCancel()
            await handleQuery()
        }
        state.isEdit = false
    } else {
        const res: ResType<any> = await addInfoBaseDepotApi(state.formState)
        if (res.data.code == 200) {
            showMsg("添加成功", 'success')
            handleCancel()
            await handleQuery()
        }
    }
}

const handleCancel = () => {
    state.isShow = false
    state.formState = {
        name: "",
        address: "",
        warehousing: 0,
        truckage: 0,
        type: 1,
        sort: 0,
        remark: "",
        enabled: true,
        isDefault: false
    }
    formRef.value?.resetFields()
}

const changePagination = async (pagination: { current: number, pageSize: number }) => {
    state.tableParams.page = pagination.current
    state.tableParams.pageSize = pagination.pageSize
    await handleQuery()
}

const handleEdit = (record: any) => {
    state.formState = { ...record }
    state.isShow = true
    state.isEdit = true
}

const handleDelete = async (record: any) => {
    try {
        const res: ResType<any> = await deleteInfoBaseDepotApi({ id: record.id })
        if (res.data.code == 200) {
            showMsg("删除成功", 'success')
            await handleQuery()
        } else {
            showMsg("删除失败", 'error')
        }
    } catch (error) {
        showMsg("删除失败", 'error')
    }
}

onMounted(async () => {
    await handleQuery()
})
</script>

<style lang="scss" scoped>
.erpInfoBaseDepot-container {
    .card-table {
        :deep(.ant-card-body) {
            height: 100%;
        }
    }
}

:deep(.ant-table-cell-fix-right) {
    // right: 0 !important;
}

:deep(.ant-btn >span) {
    display: inline-flex !important;
}
</style>